package org.teamh.connection.handler;

import java.util.LinkedList;

import org.teamh.game.Start;
import org.teamh.game.StartGame;
import org.teamh.connection.MapDownload;
import org.teamh.connection.MessageReceiver;

public class ConnectionHandler implements MessageReceiver {
	
	private Start start;
	private LinkedList<MasterHandler> handler = new LinkedList<MasterHandler>();
//	private boolean inGame;
	private MapDownload mapDownload;
	private boolean eot;
	
	private boolean handle;
	
	public ConnectionHandler(Start start) {
		this.start = start;
//		this.inGame = true;
		this.setEot(false);
		
		//add all handler here
		handler.add(new ChatHandler(start));
		handler.add(new GameHandler(start));
		handler.add(new PlayerHandler(start));
		handler.add(new LoginHandler(start));
		handler.add(new ExceptionHandler(start));
		handler.add(new MapHandler(start));
		handler.add(new JoinGameHandler(start));
		handler.add(new CreateTestPlayerHandler(start));
		
		mapDownload = new MapDownload(start);
	}
	
	@Override
	public void receiveMessage(String line) {
		handle = false;
		
		if (line == null) {
			if (start.getGui().getNifty().getCurrentScreen().getScreenId().contains("login")) {
				start.getConnection().reconnect();
			} else if (start.getGui().getNifty().getCurrentScreen().getScreenId().contains("lobby")) {
				//start.getGui().setCurrentScreen(start.getGui().getLoginScreen());
				//start.getGui().setFollowingScreen(start.getGui().getLoginScreen());
				//start.getConnection().reconnect();
				//start.getGui().addEvent(new Event("timeout", ""));
			}
		} else {
			if (line.contains("SENDING") && line.contains("BYTES")) {
				String[] lines = line.split(" ");
				mapDownload.map(Integer.parseInt(lines[1]));
			} else if (line != null) { // to evade NPE is connection
										// times out
				for (MasterHandler handler : this.handler) {
					handle = handler.handleMsg(line); // handle incoming
														// messages
					if (handle) {
						break;
					}
				}
				if (!handle) {
					if (StartGame.PRINT_MESSAGES) {
						System.out.println("No handler found for "
								+ line);
					}
				}
			}
		}
	}
	
//	public void setInGame(boolean inGame) {
//		this.inGame = inGame;
//	}
	
	public MapDownload getMapDownload() {
		return mapDownload;
	}

	public boolean isEot() {
		return eot;
	}

	public void setEot(boolean eot) {
		this.eot = eot;
	}
}
